package com.kainitram.library;

import java.util.List;
import com.kainitram.morm.Model;

import android.content.Context;
import android.content.res.Configuration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

/**
 * Basic abstract class for array adapter
 * 
 * @author Mino
 * 
 * @param <T>
 *            Type of item
 */
public abstract class BaseArrayAdapter<T extends Model> extends ArrayAdapter<T> {

	private int layoutResourceID = 0;

	public BaseArrayAdapter(Context context, int resource, List<T> objects) {
		super(context, resource, objects);
		layoutResourceID = resource;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View row = convertView;
		ViewWrapper wrapper;
		Context context = getContext();
		int orientation = context.getResources().getConfiguration().orientation;

		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(layoutResourceID, parent, false);
			wrapper = createViewWrapperForRowView(row);
			row.setTag(wrapper);
		} else {
			wrapper = (ViewWrapper) row.getTag();
		}

		T item = getItem(position);

		onBindViewToItem(item, wrapper,
				orientation == Configuration.ORIENTATION_PORTRAIT);

		return row;
	}

	/**
	 * Binding view to concret item.
	 * 
	 * @param item
	 *            represent entity.
	 * @param viewWrapper
	 *            contains view.
	 * @param isPortrait
	 *            is portrait screen orientation
	 */
	protected abstract void onBindViewToItem(T item, ViewWrapper viewWrapper,
			Boolean isPortrait);

	/**
	 * Get view wrapper for row view
	 * 
	 * @param rowView
	 *            row item view
	 * @return View wrapper for row view
	 */
	protected abstract BaseViewWrapper createViewWrapperForRowView(View rowView);
}
